package com.hdd.utils.wx;


import com.hdd.biz.task.WxMiniProgramFlushAccessTokenJob;
import com.hdd.utils.JsonUtil;
import com.hdd.utils.http.HttpClient;
import com.hdd.utils.http.OkHttpResponse;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author ;xuhu
 * @Date: 2020-11-23 17:23
**/

@Component
public class WxMiniProgramCheckUtil {

    @Autowired
    private WxMiniProgramFlushAccessTokenJob accessTokenJob;

    /**
     * 音频审核
     *
     * @param mediaUrl 音频地址
     * @return
     */
    public CheckResult mediaCheckAsync(String mediaUrl){
        String url = "https://api.weixin.qq.com/wxa/media_check_async?access_token=";

        Map<String, Object> map = new HashMap<>();
        map.put("media_url", mediaUrl);
        map.put("media_type", 1);

        return doPost(url, map);
    }

    /**
     * 音频审核
     *
     * @param imageUrl 图片地址
     * @return
     */
    public CheckResult imageCheckAsync(String imageUrl){
        String url = "https://api.weixin.qq.com/wxa/media_check_async?access_token=";

        Map<String, Object> map = new HashMap<>();
        map.put("media_url", imageUrl);
        map.put("media_type", 2);

        return doPost(url, map);
    }


    /**
     * 文字审核
     *
     * @param content 文字内容
     * @return
     */
    public CheckResult msgSecCheck(String content) {
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=";
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        return doPost(url, map);
    }

    private CheckResult doPost(String url, Map<String, Object> map) {
        CheckResult checkResult = null;
        OkHttpResponse<String> json = HttpClient.postJson(url + accessTokenJob.getAccessToken(), JsonUtil.toJsonString(map));

        if (json.isSuccess()) {
            checkResult = JsonUtil.parseObject(json.getData(), CheckResult.class);
            if (checkResult.getErrCode() == 40001) {
                json = HttpClient.postJson(url + accessTokenJob.getNewAccessToken(), JsonUtil.toJsonString(map));
                checkResult = JsonUtil.parseObject(json.getData(), CheckResult.class);
            }
        } else {
            checkResult = new CheckResult();
            checkResult.setErrCode(-1);
            checkResult.setErrMsg("请求失败");
        }

        return checkResult;
    }

    public CheckResult imgSecCheck(MultipartFile file) throws IOException {
        return imgSecCheck(file.getBytes());
    }

    /**
     * 图片审核
     *
     * @param byt
     * @return
     */
    public CheckResult imgSecCheck(byte[] byt){
        String url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=";
        CheckResult checkResult = checkPic(byt, url + accessTokenJob.getAccessToken());
        if (checkResult.getErrCode() == 40001) {
            checkResult = checkPic(byt, url + accessTokenJob.getNewAccessToken());
        }
        return checkResult;
    }

    /**
     * 图片审核
     *
     * @param urls
     * @return
     */
    public CheckResult imgSecCheck2(String urls){
        String url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=";
        CheckResult checkResult = checkPic(image2byte(urls), url + accessTokenJob.getAccessToken());
        if (checkResult.getErrCode() == 40001) {
            checkResult = checkPic(image2byte(urls), url + accessTokenJob.getNewAccessToken());
        }
        return checkResult;
    }

    /**
     * 图片转为byte数组
     *
     * @param path
     * @return
     */
    public  byte[] image2byte(String path)  {
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        try{
            url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return data;
    }


    /**
     *  图片审核
     * @param byt
     * @return
     */
    private CheckResult checkPic(byte[] byt, String url) {

        CheckResult checkResult = null;
        try {

            CloseableHttpClient httpclient = HttpClients.createDefault();

            CloseableHttpResponse response = null;

            HttpPost request = new HttpPost(url);
            request.addHeader("Content-Type", "application/octet-stream");

            request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));

            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");
            checkResult = JsonUtil.parseObject(result, CheckResult.class);

        } catch (Exception e) {
            e.printStackTrace();
            checkResult = new CheckResult();
            checkResult.setErrCode(-1);
            checkResult.setErrMsg("请求失败");
            System.out.println("----------------调用腾讯内容过滤系统出错------------------");
        }
        return checkResult;
    }

    @Setter
    @Getter
    public static class CheckResult{
        /**
         * 87014 内容不合规
         */
        private Integer errCode;
        private String errMsg;
        /**
         * 任务id，用于匹配异步推送结果,音频审核
         */
        private String trace_id;

        public boolean isCompliance(){
            return errCode == 0;
        }
    }

}